package com.yeshine.opendata.utils.mybatis;

import com.yeshine.opendata.core.AppException;
import com.yeshine.opendata.utils.PageResult;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * Created by taohj on 2014/4/17.
 */
public  class MybatisPageHelpper {


   private PageResult pageResult;


   protected int page;

   protected int size;



  private Map<String,String> databaseDialectPageHelppers;







   public   String getPageSql(StringBuffer StringBuffer,String dialect) {
       String sqlTemplate = databaseDialectPageHelppers.get(dialect);
       if (!StringUtils.hasLength(sqlTemplate)) {
           throw new AppException("cannot find  Dialect:" + dialect + "from  databaseDialectPageHelppers");
       }



       sqlTemplate = sqlTemplate.replace("~sql~", StringBuffer.toString()).replaceAll("~start~", getRowStart() + "").replace("~end~", getRowEnd() + "");
       return sqlTemplate;

   }


   public int getRowStart(){
       int page=this.page;
       int size=this.size;

       if (pageResult!=null){
           if (pageResult.getPage()!=null && pageResult.getPage()!=0 ){page=pageResult.getPage();}else {pageResult.setPage(page);}
           if (pageResult.getSize()!=null &&pageResult.getSize()!=0){size=pageResult.getSize();}else{pageResult.setSize(size);}
       }


       return  (page-1)*size;




   }

    public  int getRowEnd(){
        int page=this.page;
        int size=this.size;
        if (pageResult!=null){
            if (pageResult.getPage()!=null && pageResult.getPage()!=0 ){page=pageResult.getPage();}else {pageResult.setPage(page);}
            if (pageResult.getSize()!=null &&pageResult.getSize()!=0){size=pageResult.getSize();}else{pageResult.setSize(size);}
        }

        return  size;
    }


    public void setPage(int page) {
        this.page = page;
    }

    public void setSize(int size) {
        this.size = size;
    }


    public PageResult getPageResult() {
        return pageResult;
    }

    public void setPageResult(PageResult pageResult) {
        this.pageResult = pageResult;
    }


    public int getPage() {
        return page;
    }

    public int getSize() {
        return size;
    }

    public Map<String, String> getDatabaseDialectPageHelppers() {
        return databaseDialectPageHelppers;
    }

    public void setDatabaseDialectPageHelppers(Map<String, String> databaseDialectPageHelppers) {
        this.databaseDialectPageHelppers = databaseDialectPageHelppers;
    }

    public static void main(String[] args) {
        String a="&sql&  ---";
        a=a.replaceAll("&sql&","---");
        System.out.println(a);
    }
}
